// index.js
const app = getApp()
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
import {
    uploadUserInfo
} from '../../network/api'
import {
    baseUrl
} from '../../network/requestUrl'
Page({
    data: {
        avatarUrl: defaultAvatarUrl,
        theme: wx.getSystemInfoSync().theme,
        fileName: '',
        isDisabled: true
    },
    onLoad() {
        wx.onThemeChange((result) => {
            this.setData({
                theme: result.theme
            })
        })
    },
    onChooseAvatar(e) {
        const {
            avatarUrl
        } = e.detail
        this.setData({
            avatarUrl,
        })
        this.upload_file(avatarUrl)
    },
    upload_file(filePath) {
        var that = this;
        var formData = {}; // HTTP 请求中其他额外的参数信息
        wx.uploadFile({
            url: `${baseUrl}common/upload`, //后台处理接口
            filePath: filePath,
            name: 'file',
            header: {
                'content-type': 'multipart/form-data',
                'Authorization': wx.getStorageSync('token')
            }, // 设置请求的 header
            formData: formData,
            success: function (res) {
                if (res.data) {
                    const data = JSON.parse(res.data)
                    that.setData({
                        fileName: data.fileName,
                        isDisabled: false
                    })
                }
                wx.showToast({
                    title: '上传成功',
                })
            },
            fail: function (res) {
                wx.showModal({
                    title: '提示',
                    content: res.msg,
                })
            }
        })
    },
    formSubmit(e) {
        if (e.detail.value.nickname && this.data.fileName) {
            this.saveData(this.data.fileName, e.detail.value.nickname)
        } else {
            wx.showModal({
                title: '提示',
                content: `name${e.detail.value.nickname}--avatar${this.data.fileName}`,
            })
        }
    },
    async saveData(fileName, nickname) {
        const params = {
            avatar: fileName,
            nickName: nickname
        }
        const res = await uploadUserInfo(params)
        if (res.code === 200) {
            wx.setStorageSync('nickName', params.nickName)
            wx.setStorageSync('avatarUrl', params.avatar)
            setTimeout(() => {
                wx.navigateBack()
            }, 500)
        } else {
            wx.showModal({
                title: '提示',
                content: res.msg,
            })
        }
    },
    onUnload() {
        const page = getCurrentPages()
        const beforePage = page[page.length - 2]
        beforePage.onLoad()
    },
})